package com.ruoyi.hk.service.impl;

import com.ruoyi.hk.domain.DocConversation;
import com.ruoyi.hk.domain.DocMsg;
import com.ruoyi.hk.domain.User;
import com.ruoyi.hk.websocket.ChatWebSocketServer;
import com.ruoyi.hk.domain.vo.DocMessageVo;
import com.ruoyi.hk.domain.vo.UserConversationVO;
import com.ruoyi.hk.domain.vo.UserVo;
import com.ruoyi.hk.mapper.message.DocConversationMapper;
import com.ruoyi.hk.mapper.message.DocMessageMapper;
import com.ruoyi.hk.service.DocMessageService;
import com.ruoyi.hk.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class DocMessageServiceImpl implements DocMessageService {
    //targetId是接受方的id

    @Autowired
    private DocMessageMapper docMessageMapper;

    @Autowired
    private DocConversationMapper docConversationMapper;

    @Autowired
    private UserService userService;

    @Override
//    @Cacheable(cacheNames = "chatHistory", keyGenerator = "keyGenerator")
    public List<DocMessageVo> getChatHistory(Long userId, Long targetId) {
        List<DocMsg> rawMessages = docMessageMapper.getChatHistory(userId, targetId);

        // 转换为DocMessageVo列表
        List<DocMessageVo> result = new ArrayList<>();

        for (DocMsg rawMessage : rawMessages) {
            // 使用现有的convertToVO方法进行转换
            DocMessageVo vo = convertToVO(rawMessage);
            result.add(vo);
        }

        return result;
    }


    @Override
    @Transactional
    public DocMessageVo sendMessage(Long senderId, Long receiverId, String content, Integer messageType) {
        // 创建消息
        DocMsg message = new DocMsg();

        message.setSenderId(senderId);
        message.setReceiverId(receiverId);
        message.setContent(content);
        message.setMessageType(messageType);
        message.setIsRead(0);
        message.setSendTime(LocalDateTime.now());

        // 保存消息
        docMessageMapper.save(message);

        // 更新或创建会话
        updateConversation(senderId, receiverId, message.getMsgId(), message.getSendTime());

        // 转换为VO
        DocMessageVo messageVO = convertToVO(message);

        // 通过WebSocket发送给接收者
        ChatWebSocketServer.sendMessageToUser(receiverId, messageVO);

        return messageVO;
    }


    @Override
//    @Cacheable(cacheNames = "userConversations", keyGenerator = "keyGenerator")
    public List<DocMessageVo> getUserConversations(Long userId) {
        //获取用户的所有会话
        Map<String,Object> params = new HashMap<>();
        params.put("userId",userId);
        List<DocConversation> conversations = docConversationMapper.selectConversationsByUserId(params);

        List<DocMessageVo> result = new ArrayList<>();

        for (DocConversation conv : conversations) {
            //确定对方用户的id
            Long otherUserId = conv.getUser1Id().equals(userId) ? conv.getUser2Id() : conv.getUser1Id();

            //获取对方用户id
            User otherUser = userService.getById(otherUserId);
            if (otherUser != null){
                DocMessageVo vo = new DocMessageVo();
                vo.setMsgId(conv.getConverId());
                vo.setSenderId(otherUserId); //发送者id
                vo.setReceiverId(userId); //接收者id

                //设置发送者信息
                UserVo senderVo = new UserVo();
                senderVo.setUserId(otherUserId);
                senderVo.setNickName(otherUser.getNickName());

                // 处理头像：添加默认头像判断
                String avatar = otherUser.getAvatar();
                String userType = otherUser.getUserType();

                if (needDefaultAvatar(avatar)) {
                    if ("102".equals(userType)) {
                        // 医生：使用默认医生头像
                        avatar = "/src/assets/images/医生默认头像.png";
                    } else if ("00".equals(userType)) {
                        // 管理员：使用默认管理员头像
                        avatar = "/src/assets/images/profile.jpg";
                    } else {
                        // 普通用户：使用默认用户头像
                        avatar = "/src/assets/images/profile.jpg";
                    }
                }
                senderVo.setAvatar(avatar);

                vo.setSender(senderVo);

                vo.setContent(conv.getLastMessageId() != null ? "点击查看最新消息" : "暂无消息");
                vo.setSendTime(conv.getLastMessageTime());

                //设置未读消息数
                if (conv.getUser1Id().equals(userId)){
                    vo.setUnreadCount(conv.getUnreadCount1());
                }else {
                    vo.setUnreadCount(conv.getUnreadCount2());
                }
                result.add(vo);
            }
        }
        return result;
    }

    @Override
//    @Cacheable(cacheNames = "userConversationsWithUserInfo", keyGenerator = "keyGenerator")
    public List<UserConversationVO> getUserConversationsWithUserInfo(Long userId) {
        // 获取用户的所有会话（包含完整的用户信息）
        Map<String,Object> params = new HashMap<>();
        params.put("userId",userId);
        List<DocConversation> conversations = docConversationMapper.selectConversationsByUserId(params);

        List<UserConversationVO> result = new ArrayList<>();

        for (DocConversation conv : conversations) {
            // 确定对方用户ID
            Long otherUserId = conv.getUser1Id().equals(userId) ? conv.getUser2Id() : conv.getUser1Id();

            // 获取对方用户信息
            User otherUser = userService.selectById(otherUserId);
            if (otherUser != null) {
                UserConversationVO vo = new UserConversationVO();
                vo.setUserId(otherUserId);
                vo.setUserName(otherUser.getUserName());
                vo.setNickName(otherUser.getNickName());

                // 处理头像：添加默认头像判断
                String avatar = otherUser.getAvatar();
                String userType = otherUser.getUserType();

                if (needDefaultAvatar(avatar)) {
                    if ("102".equals(userType)) {
                        // 医生：使用默认医生头像
                        avatar = "/src/assets/images/医生默认头像.png";
                    } else if ("00".equals(userType)) {
                        // 管理员：使用默认管理员头像
                        avatar = "/src/assets/images/profile.jpg";
                    } else {
                        // 普通用户：使用默认用户头像
                        avatar = "/src/assets/images/profile.jpg";
                    }
                }
                vo.setAvatar(avatar);

                vo.setEmail(otherUser.getEmail());
                vo.setUserType(otherUser.getUserType());
                vo.setStatus(otherUser.getStatus());
                vo.setLastMessageTime(conv.getLastMessageTime());

                // 设置未读消息数
                if (conv.getUser1Id().equals(userId)) {
                    vo.setUnreadCount(conv.getUnreadCount1());
                } else {
                    vo.setUnreadCount(conv.getUnreadCount2());
                }

                // 获取最后一条消息内容
                if (conv.getLastMessageId() != null) {
                    DocMsg lastMessage = docMessageMapper.selectById(conv.getLastMessageId());
                    if (lastMessage != null) {
                        DocMsg docMsg = new DocMsg();
                        docMsg.setMsgId(lastMessage.getMsgId());
                        docMsg.setContent(lastMessage.getContent());

                        vo.setDocMsg(docMsg);
                    }
                }
                result.add(vo);
            }
        }

        return result;
    }

    @Override
//    @Cacheable(cacheNames = "allOtherUsers", keyGenerator = "keyGenerator")
    public List<UserConversationVO> getAllOtherUsers(Long userId) {

        // 获取所有其他用户（排除当前用户）
        Map<String,Object> params = new HashMap<>();
        params.put("userId",userId);
        params.put("status",0);

        List<User> userList = userService.getUserAll(params);

        List<UserConversationVO> result = new ArrayList<>();

        for (User user : userList) {
            // 使用convertUserToConversationVO方法处理头像
            UserConversationVO vo = convertUserToConversationVO(user);

            // 获取与当前用户的未读消息数
            Integer unreadCount = getUnreadCount(userId, user.getUserId());
            vo.setUnreadCount(unreadCount);

            // 获取最后一条消息信息
            Map<String,Object> messageParams = new HashMap<>();
            messageParams.put("userId1",userId);
            messageParams.put("userId2",user.getUserId());
            DocMsg lastMessage = docMessageMapper.selectLastMessageBetweenUsers(messageParams);

            if (lastMessage != null) {
                DocMsg docMsg = new DocMsg();
                vo.setLastMessageTime(lastMessage.getSendTime());
                docMsg.setContent(lastMessage.getContent());
                vo.setDocMsg(docMsg);
            }

            result.add(vo);
        }
        return result;
    }

    /**
     * 根据用户角色获取聊天用户列表
     */
    @Override
//    @Cacheable(cacheNames = "chatUserList", keyGenerator = "keyGenerator")
    public List<UserConversationVO> getChatUserList(Long userId) {
        List<UserConversationVO> result = new ArrayList<>();

        // 获取当前用户信息
        User currentUser = userService.getById(userId);
        if (currentUser == null) {
            return result;
        }

        // 获取所有管理员用户（管理员ID为1）
        List<User> adminUsers = docMessageMapper.selectAdminUsers();

        // 根据用户类型获取不同的用户列表
        String userType = currentUser.getUserType();

        if ("00".equals(userType)) {
            result = getAllOtherUsers(userId);
        } else if ("102".equals(userType)) {
            result = getDoctorChatUserList(currentUser, adminUsers);
        } else {
            result = getNormalUserChatUserList(currentUser, adminUsers);
        }

        return result;
    }

    /**
     * 获取医生的聊天用户列表
     */
    private List<UserConversationVO> getDoctorChatUserList(User doctor, List<User> adminUsers) {
        List<UserConversationVO> result = new ArrayList<>();

        // 添加管理员到列表
        for (User admin : adminUsers) {
            if (!admin.getUserId().equals(doctor.getUserId())) {
                UserConversationVO vo = convertUserToConversationVO(admin);
                // 获取未读消息数
                Integer unreadCount = getUnreadCount(doctor.getUserId(), admin.getUserId());
                vo.setUnreadCount(unreadCount);
                result.add(vo);
            }
        }

        // 检查医生是否有团队
        if (doctor.getTeamId() != null) {
            // 获取团队下的所有医生
            List<User> teamDoctors = docMessageMapper.selectDoctorsByTeamId(doctor.getTeamId());

            for (User teamDoctor : teamDoctors) {
                if (!teamDoctor.getUserId().equals(doctor.getUserId())) {
                    UserConversationVO vo = convertUserToConversationVO(teamDoctor);
                    // 获取未读消息数
                    Integer unreadCount = getUnreadCount(doctor.getUserId(), teamDoctor.getUserId());
                    vo.setUnreadCount(unreadCount);
                    result.add(vo);
                }
            }

            // 获取签约该团队的家庭ID列表
            List<Long> familyIds = docMessageMapper.selectFamilyIdsByTeamId(doctor.getTeamId().longValue());

            // 获取这些家庭下的所有用户
            for (Long familyId : familyIds) {
                List<User> familyUsers = docMessageMapper.selectUsersByFamilyId(familyId);

                for (User familyUser : familyUsers) {
                    UserConversationVO vo = convertUserToConversationVO(familyUser);
                    // 获取未读消息数
                    Integer unreadCount = getUnreadCount(doctor.getUserId(), familyUser.getUserId());
                    vo.setUnreadCount(unreadCount);
                    result.add(vo);
                }
            }
        }
        return result;
    }

    /**
     * 获取普通用户的聊天用户列表
     */
    private List<UserConversationVO> getNormalUserChatUserList(User user, List<User> adminUsers) {
        List<UserConversationVO> result = new ArrayList<>();

        // 添加管理员到列表
        for (User admin : adminUsers) {
            if (!admin.getUserId().equals(user.getUserId())) {
                UserConversationVO vo = convertUserToConversationVO(admin);
                // 获取未读消息数
                Integer unreadCount = getUnreadCount(user.getUserId(), admin.getUserId());
                vo.setUnreadCount(unreadCount);
                result.add(vo);
            }
        }

        // 检查用户是否加入家庭
        Long familyId = docMessageMapper.selectFamilyIdByUserId(user.getUserId());

        if (familyId != null) {
            // 获取家庭下的所有用户
            List<User> familyUsers = docMessageMapper.selectUsersByFamilyId(familyId);
            for (User familyUser : familyUsers) {
                if (!familyUser.getUserId().equals(user.getUserId())) {
                    UserConversationVO vo = convertUserToConversationVO(familyUser);
                    // 获取未读消息数
                    Integer unreadCount = getUnreadCount(user.getUserId(), familyUser.getUserId());
                    vo.setUnreadCount(unreadCount);
                    result.add(vo);
                }
            }

            // 获取家庭签约的团队ID
            String teamIdsStr = docMessageMapper.selectTeamIdByUserId(user.getUserId());

            if (teamIdsStr != null && !teamIdsStr.trim().isEmpty()) {
                // 分割逗号分隔的团队ID
                String[] teamIdArray = teamIdsStr.split(",");
                
                for (String teamIdStr : teamIdArray) {
                    if (teamIdStr != null && !teamIdStr.trim().isEmpty()) {
                        try {
                            Integer teamId = Integer.parseInt(teamIdStr.trim());
                            // 获取该团队下的所有医生
                            List<User> teamDoctors = docMessageMapper.selectDoctorsByTeamId(teamId);
                            for (User teamDoctor : teamDoctors) {
                                UserConversationVO vo = convertUserToConversationVO(teamDoctor);
                                // 获取未读消息数
                                Integer unreadCount = getUnreadCount(user.getUserId(), teamDoctor.getUserId());
                                vo.setUnreadCount(unreadCount);
                                result.add(vo);
                            }
                        } catch (NumberFormatException e) {
                            // 忽略无效的团队ID格式，继续处理其他团队ID
                        }
                    }
                }
            }
        }

        return result;
    }

    /**
     * 将User对象转换为UserConversationVO对象
     */
    private UserConversationVO convertUserToConversationVO(User user) {
        UserConversationVO vo = new UserConversationVO();
        vo.setUserId(user.getUserId());
        vo.setUserName(user.getUserName());
        vo.setNickName(user.getNickName());

        // 处理头像：根据用户类型设置不同的默认头像
        String avatar = user.getAvatar();
        String userType = user.getUserType();

        if (needDefaultAvatar(avatar)) {
            if ("102".equals(userType)) {
                // 医生：使用默认医生头像
                avatar = "/src/assets/images/医生默认头像.png";
            } else if ("00".equals(userType)) {
                // 管理员：使用默认管理员头像
                avatar = "/src/assets/images/profile.jpg";
            } else {
                // 普通用户：使用默认用户头像
                avatar = "/src/assets/images/profile.jpg";
            }
        }

        vo.setAvatar(avatar);

        vo.setEmail(user.getEmail());
        vo.setUserType(user.getUserType());
        vo.setStatus(user.getStatus());

        return vo;
    }

    /**
     * 检查用户是否需要设置默认头像
     */
    private boolean needDefaultAvatar(String avatar) {

        if (avatar == null || avatar.trim().isEmpty()) {
            return true;
        }

        // 检查是否为默认头像文件名
        String[] defaultAvatarNames = {
                "医生默认头像.png",
                "医生默认头像.jpg",
                "医生默认头像.jpeg",
                "profile.jpg",
                "profile.png",
                "doctor.png"
        };
        for (String defaultName : defaultAvatarNames) {
            if (defaultName.equals(avatar)) {
                return true;
            }
        }
        return false;
    }

    @Override
    @Transactional
    public void markMessagesAsRead(Long userId, Long targetId) {
        // 标记消息为已读 -- 查出来接收方和发送方的未读信息
        Map<String,Object> params = new HashMap<>();
        params.put("receiverId",userId);
        params.put("senderId",targetId);

        docMessageMapper.updateMsg(params);

        // 更新会话中的未读消息数
        updateConversationUnreadCount(userId, targetId, Integer.valueOf(0));
    }

    @Override
//    @Cacheable(cacheNames = "unreadCount", keyGenerator = "keyGenerator")
    public Integer getUnreadCount(Long userId, Long targetId) {
        // 获取未读消息数
        Map<String,Object> params = new HashMap<>();
        params.put("receiverId", userId);
        params.put("senderId", targetId);
        Integer counts = docMessageMapper.count(params);

        return counts;
    }

    /**
     * 更新或创建会话
     */
    private void updateConversation(Long user1Id, Long user2Id, Long lastMessageId, LocalDateTime lastMessageTime) {
        // 查找现有会话
        Map<String,Object> params = new HashMap<>();
        params.put("user1Id", user1Id);
        params.put("user2Id", user2Id);

        DocConversation conversation = docConversationMapper.selectByUserId(params);

        if (conversation == null) {
            // 创建新会话
            conversation = new DocConversation();
            conversation.setUser1Id(user1Id);
            conversation.setUser2Id(user2Id);
            conversation.setLastMessageId(lastMessageId);
            conversation.setLastMessageTime(lastMessageTime);
            conversation.setUnreadCount1(0);
            conversation.setUnreadCount2(0);

            // 设置接收者的未读消息数+1
            if (user1Id.equals(user2Id)) {
                conversation.setUnreadCount1(1);
            } else {
                conversation.setUnreadCount2(1);
            }

            docConversationMapper.insertConversation(conversation);
        } else {
            // 更新现有会话
            conversation.setLastMessageId(lastMessageId);
            conversation.setLastMessageTime(lastMessageTime);

            // 增加接收者的未读消息数
            if (conversation.getUser1Id().equals(user2Id)) {
                Integer currentCount = conversation.getUnreadCount1() != null ? conversation.getUnreadCount1() : 0;
                conversation.setUnreadCount1(currentCount + 1);
            } else {
                Integer currentCount = conversation.getUnreadCount2() != null ? conversation.getUnreadCount2() : 0;
                conversation.setUnreadCount2(currentCount + 1);
            }
            docConversationMapper.updateConversation(conversation);
        }
    }

    /**
     * 更新会话中的未读消息数
     */
    private void updateConversationUnreadCount(Long userId, Long targetId, Integer newCount) {
        Map<String,Object> params = new HashMap<>();
        params.put("userId",userId);
        params.put("targetId",targetId);

        DocConversation conversation = docConversationMapper.selectByUserId(params);

        if (conversation != null) {
            if (conversation.getUser1Id().equals(userId)) {
                conversation.setUnreadCount1(newCount);
            } else {
                conversation.setUnreadCount2(newCount);
            }
            docConversationMapper.updateConversation(conversation);
        }
    }

    /**
     * 转换为VO
     */
    private DocMessageVo convertToVO(DocMsg message) {
        DocMessageVo vo = new DocMessageVo();
        vo.setMsgId(message.getMsgId());
        vo.setSenderId(message.getSenderId());
        vo.setReceiverId(message.getReceiverId());
        vo.setContent(message.getContent());
        vo.setMessageType(message.getMessageType());
        vo.setIsRead(message.getIsRead());
        vo.setSendTime(message.getSendTime());

        // 获取发送者信息,并封装为UserVo
        User sender = userService.getById(message.getSenderId());
        if (sender != null) {
            UserVo senderVo = new UserVo();
            senderVo.setNickName(sender.getNickName());

            // 处理发送者头像 - 添加调试信息
            String senderAvatar = sender.getAvatar();
            String processedSenderAvatar = processedAvatar(senderAvatar, sender.getUserType());
            senderVo.setAvatar(processedSenderAvatar);

            vo.setSender(senderVo);
        }

        // 获取接收者信息，并封装为UserVo
        User receiver = userService.getById(message.getReceiverId());
        if (receiver != null) {
            UserVo receiverVo = new UserVo();
            receiverVo.setNickName(receiver.getNickName());

            // 处理接收者头像 - 添加调试信息
            String receiverAvatar = receiver.getAvatar();
            String processedReceiverAvatar = processedAvatar(receiverAvatar, receiver.getUserType());
            receiverVo.setAvatar(processedReceiverAvatar);

            vo.setReceiver(receiverVo);
        }

        return vo;
    }

    /**
     * 根据用户类型和头像状态，返回正确的头像路径
     */
    private String processedAvatar(String originalAvatar, String userType) {
        if (needDefaultAvatar(originalAvatar)) {
            if ("102".equals(userType)) {
                // 医生：使用医生默认头像
                String doctorAvatar = "/src/assets/images/医生默认头像.png";
                return doctorAvatar;
            } else {
                // 其他用户：使用普通默认头像
                String defaultAvatar = "/src/assets/images/profile.jpg";
                return defaultAvatar;
            }
        } else {
            return originalAvatar;
        }
    }
}
